package com.ttbj.order.component;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ttbj.cargo.dao.CargoMapper;
import com.ttbj.cargo.po.Cargo;
import com.ttbj.core.util.DtoTransitionUtils;
import com.ttbj.order.dao.OrderMapper;
import com.ttbj.order.po.Order;
import com.ttbj.product.api.OwnerFacade;
import com.ttbj.product.api.WaybillFacade;
import com.ttbj.product.bean.dto.CargoDto;
import com.ttbj.product.bean.dto.DriverDto;
import com.ttbj.product.bean.dto.OrderDto;
import com.ttbj.product.bean.dto.OwnerDto;
import com.ttbj.util.Assert;

@Component
public class OrderComponent {

	@Autowired
	private OrderMapper orderMapper = null;

	@Autowired
	private CargoMapper cargoMapper = null;

	@Autowired
	private OwnerFacade ownerFacade = null;

	@Autowired
	private WaybillFacade waybillFacade = null;

	/**
	 * 注意添加openId
	 * 有寄件人收件人以及货物和车辆信息的订单信息表
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	public OrderDto orderDetails(OrderDto dto) throws Exception {
		if (!Assert.assertNonNullField0(dto, "orderId")) {
			return null;
		}
		Order order = orderMapper.selectByPrimaryKey(dto.getOrderId());
		Long orderSender = order.getOrderSender();
		Long orderCargo = order.getOrderCargo();
		Long orderReciver = order.getOrderReciver();
		String openId = dto.getOpenId();
		Cargo cargo = cargoMapper.selectByPrimaryKey(orderCargo);
		OwnerDto sender = ownerFacade.getOwner(openId, orderSender, 0);
		OwnerDto reciver = ownerFacade.getOwner(openId, orderReciver, 1);
		List<DriverDto> drivers = waybillFacade.allDriver(dto.getOrderId());
		if (null != cargo) {
			CargoDto cargoDto = (CargoDto) DtoTransitionUtils.trans(CargoDto.class, cargo);
			dto.setCargoDto(cargoDto);
		}
		dto.setSender(sender);
		dto.setReciver(reciver);
		dto.setDrivers(drivers);
		return dto;
	}

	/**
	 * 只包含寄件人和收件人的订单信息
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	public OrderDto orderDetail(Long orderId) throws Exception {
		if(null == orderId){
			return null;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (order == null) {
			return null;
		}
		OwnerDto sender = ownerFacade.getOwner(null, order.getOrderSender(), 0);
		OwnerDto reciver = ownerFacade.getOwner(null, order.getOrderReciver(), 1);
		OrderDto dto = (OrderDto)DtoTransitionUtils.trans(OrderDto.class, order);
		dto.setSender(sender);
		dto.setReciver(reciver);
		return dto;
	} 
	
	 
	/**
	 * 设置自动已完成改为手动
	 * @param autoComple
	 * @param orderId
	 */
	public void setAutoComple(Long orderId){
			Order order = new  Order(orderId);
			order.setOrderAutoComple(0);
			orderMapper.updateByPrimaryKeySelective(order);
	}
	

}
